package com.atguigu.controller;

import com.atguigu.domain.Role;
import com.atguigu.domain.UserInfo;
import com.atguigu.service.UserService;
import com.itheima.ssm.utils.BCryptPasswordEncoderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("findAll.do")
    public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<UserInfo> users= userService.findAll();
        mv.addObject("userList",users);
        mv.setViewName("user-list");
        return mv;
    }

    @RequestMapping("save.do")
    @PreAuthorize("authentication.principal.username=='admin'")
    public String sava(UserInfo userInfo){
        String encoderPasswor = BCryptPasswordEncoderUtils.EncoderPasswor(userInfo.getPassword());
        userInfo.setPassword(encoderPasswor);
        userService.sava(userInfo);
        return "redirect:findAll.do";
    }

    //查询指定id的用户
    @RequestMapping("findById.do")
    public ModelAndView findById(String id){
        ModelAndView mv = new ModelAndView();
        UserInfo user= userService.findById(id);
        mv.addObject("user",user);
        mv.setViewName("user-show");
        return mv;
    }

    //查询用户以及用户可以添加的角色
    @RequestMapping("findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id",required = true) String id){
        ModelAndView mv = new ModelAndView();
        //1.根据id查询用户
        UserInfo user= userService.findById(id);
        //2.根据用户id查询可以添加的角色
        List<Role> otherRoles = userService.findOtherRoles(id);
        mv.addObject("roleList",otherRoles);
        mv.addObject("user",user);
        mv.setViewName("user-role-add");
        return mv;
    }

    @RequestMapping("addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId",required = true) String userId,
                                  @RequestParam(name = "ids",required = true) String[] roleIds){
        userService.saveuserAndRole(userId,roleIds);
        return "redirect:findAll.do";
    }
}
